<template>
  <view
    class="cin"
    :class="[cinMove !== 0 ? 'cin-active' : '']"
    :style="{
      transform: `translate(-50%,${-cinMove}px)`,
      opacity: `${(700 - cinMove) / 100}`,
      borderRadius: `${((cinMove + 50) / 300) * 5}px`,
      width: `${100 - (cinMove / 100) * 2.5}%`,
      transition: `${cinTransition}`,
      boxShadow: `0px 0px 15px rgba(0, 0, 0,${(cinMove / 200) * 0.5} )`,
    }"
    @touchstart="TapStartCin"
    @touchmove="TouchMove"
    @touchend="TapEndCin"
  >
    <view class="cin-key-box" :style="{borderTop: `5px solid ${moneyOut?'white':'rgb(228, 192, 12)'}`}">
      <view class="cin-key-box-up">
        <view class="cin-key-value"
          >¥ {{ pay.price === '' ? '0' : pay.price }}</view
        >
        <input
          class="cin-name"
          v-model="pay.name"
          placeholder="写点什么..."
          @confirm="OverInput"
        />
      </view>
      <view class="cin-tap">
        <view class="cin-tap-list">
          <view
            v-for="(item, index) in option?.tap"
            :key="index"
            class="cin-tap-item"
            :class="[tapClick === index ? 'cin-tap-item-up' : '']"
            :style="{
              background: `${item.background}`,
              color: `${item.color}`,
            }"
            @tap="CinTap(item, index)"
            @longpress="DelTap(index)"
            @touchstart="TapStartTap"
            @touchend="TapEndTap"
          >
            &nbsp;{{ item.name }}&nbsp;
          </view>
        </view>
        <input
          class="add-tap-input"
          v-model="tap.name"
          @confirm="OverAddTap"
          @focus="AddTap"
        />
      </view>
    </view>
    <view
      class="keys"
      :style="{
        borderRadius: `${((cinMove + (cinMove === 0 ? 0 : 50)) / 300) * 15}px`,
      }"
    >
      <view
        v-for="(item, index) in keys"
        :key="index"
        class="keyd"
        :class="[move===0&&movepX===0?'key':'']"
        @tap="CinKey(item.value)"
        @touchend="cinTapEnd"
        @longtap="logTapCinKey(item.value)"
        >{{ item.name }}</view
      >
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onShow, onHide, onLoad } from '@dcloudio/uni-app';
import type {
  optionType,
  paymentListType,
  tapType,
  todayType,
} from '@/types/bill';
import { useBillStore } from '@/stores/bill';

//变量区
const billStore = useBillStore();
let cinTransition = ref<string>('');
let addTapText = ref<string>('+');
let tapClick = ref<number>(-1);
let state = ref<number>(-1);
let move = ref<number>(0);// y轴
let movepX = ref<number>(0);// x轴
let keys = ref<Array<{ name: string; classList: string; value: string }>>([]);
let cinMoveStartY: number = 0;
let cinMoveStartX: number = 0;
let cinMove = ref<number>(0);
let cinMoveBtn = 1;
let tap = ref<tapType>({
  name: '+',
  background: '',
  color: '',
});
let today = ref<todayType>({
  year: 0,
  month: 0,
  day: 0,
  paymentList: [],
});
let pay = ref<paymentListType>({
  name: '',
  price: '',
  time: '',
  label: {
    background: '',
    name: '',
    color: '',
  },
});
let option = ref<optionType>({
  tap: [
    {
      name: '',
      background: '',
      color: '',
    },
  ],
  dayQuota: 0,
});
let tapCss = [
  {
    b: 'rgb(100,72,52)',
    c: 'rgb(255,255,255)',
  },
  {
    b: 'rgb(130,73,32)',
    c: 'rgb(255,255,255)',
  },
  {
    b: 'rgb(215,99,95)',
    c: 'rgb(255,255,255)',
  },
];
let modBtn = false;
let modBill = {
  year: 0,
  month: 0,
  day: 0,
  index: 0,
};
let moneyOut=true

////函数区
onLoad(() => {
  console.log('cin Load');
  Init();
});
onShow(() => {
  console.log('cin Show');
});
onHide(() => {
  console.log('cin Hide');
});

//标签开始触摸
function TapStartTap() {
  cinMoveBtn = 0;
}
//标签停止触摸
function TapEndTap() {
  cinMoveBtn = 1;
}

//完成商品名输入
function OverInput() {
  if (pay.value.price !== ''&& !modBtn) {
    cinTransition.value = 'all ease 1s';
    state.value = 1;
    cinMove.value = 700;
    CinBill();
    setTimeout(function () {
      cinTransition.value = '';
      cinMove.value = -800;
    }, 500);
    uni.$emit('modBillOver');
  }
}
//完成标签输入
function OverAddTap() {
  if (option.value.tap.find((item) => item.name === tap.value.name)) {
    tap.value.name = '重复';
    addTapText.value = '';
    setTimeout(function () {
      tap.value.name = '+';
    }, 500);
  } else if (tap.value.name !== '') {
    let random = Math.floor(Math.random() * tapCss.length);
    tap.value.background = tapCss[random].b;
    tap.value.color = tapCss[random].c;
    let tempTap: tapType = { ...tap.value };
    billStore.AddTap(tempTap);
    tap.value.name = '+';
    GetOption();
  } else {
    tap.value.name = '+';
  }
}
//添加标签
function AddTap() {
  tap.value.name = '';
}
//输入标签
function CinTap(str: tapType, index: number) {
  if (index === tapClick.value) {
    tapClick.value = -1;
    pay.value.label = { name: '', background: '', color: '' };
  } else {
    pay.value.label = str;
    tapClick.value = index;
  }
}
//删除标签
function DelTap(index: number) {
  option.value.tap[index].name = '删除';
  option.value.tap[index].background = 'red';
  setTimeout(function () {
    billStore.DelTap(index);
  }, 500);
  GetOption();
}
//提交账单
function CinBill() {
  console.log('添加');
  if (pay.value.price.length !== 0) {
    if(!moneyOut){
      pay.value.price="-"+pay.value.price
    }
    pay.value.time = getCurrentTime();
    let temp = { ...pay.value };
    temp.label = { ...pay.value.label };
    billStore.AddDayBill(
      today.value.year,
      today.value.month,
      today.value.day,
      (temp = JSON.parse(JSON.stringify(temp))),
    );
    uni.$emit('upDateBoard');
    GetDayData(today.value.year, today.value.month, today.value.day);
    setTimeout(function () {
      pay.value = {
        price: '',
        name: '',
        time: '',
        label: { name: '' },
      };
    }, 500);
  }
}
//修改账单
uni.$on('modBill', function (data) {
  uni.$emit('showCalByIndex', false);
  cinTransition.value = '0';
  cinMove.value = -500;
  setTimeout(() => {
    cinTransition.value = 'all ease 0.5s';
    cinMove.value = 0;
    state.value = -1;
    pay.value = data.data;
    if(Number(pay.value.price)<0){
      moneyOut=false
      pay.value.price=String(-Number(pay.value.price))
    }
    tapClick.value = -1;
    option.value.tap.map((item, index) => {
      if (item.name === pay.value.label.name) {
        tapClick.value = index;
      }
    });
    modBtn = true;
    modBill.year = data.year;
    modBill.month = data.month;
    modBill.day = data.day;
    modBill.index = data.index;
  });
});
//发送修改的账单
function ModBill() {
  if(!moneyOut){
      pay.value.price="-"+pay.value.price
  }
  let temp = { ...pay.value };
  temp.label = { ...pay.value.label };
  temp = JSON.parse(JSON.stringify(temp));
  billStore.ModBill(
    modBill.year,
    modBill.month,
    modBill.day,
    temp,
    modBill.index,
  );
  uni.$emit('upDateBoard');
  GetDayData(today.value.year, today.value.month, today.value.day);
  setTimeout(function () {
    pay.value = {
      price: '',
      name: '',
      time: '',
      label: { name: '' },
    };
  }, 500);
  uni.$emit('modBillOver');
}
//获取当前时分秒
function getCurrentTime() {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');

  return `${hours}:${minutes}:${seconds}`;
}
//手指触碰输入板
function TapStartCin(event: TouchEvent) {
  if (cinMoveBtn) {
    cinMoveStartY = event.touches[0].clientY;
    cinMoveStartX = event.touches[0].clientX;
    cinTransition.value = '';
    move.value = 0;
    state.value = 0;
  }
  movepX.value=0
}
//手指离开输入板
function TapEndCin() {
  if (cinMoveBtn) {
    if (move.value < 100 && state.value === 0) {
      cinMove.value = 0;
      cinTransition.value = 'all ease 1s';
    }
  }
  if( movepX.value!==0){
    moneyOut=!moneyOut
  }
}

//手指移动
function TouchMove(event: TouchEvent) {
  let moveX=cinMoveStartX - event.touches[0].clientX
  let moveY=cinMoveStartY - event.touches[0].clientY
  if(moveY>=0&&Math.abs(moveY)>Math.abs(moveX)){
    if (cinMoveBtn) {
      move.value = cinMoveStartY - event.touches[0].clientY;
      if (move.value < 100 && move.value >= 0 && state.value === 0) {
        cinMove.value = move.value;
      }
      if (move.value >= 100 && state.value === 0) {
        cinTransition.value = 'all ease 1s';
        state.value = 1;
        cinMove.value = 700;
        if (!modBtn) {
          CinBill();
        } else {
          ModBill();
        }
      }
    }
  }else if(moveY>=0){
    movepX.value=moveX
  }
}

// 定义一个变量来保存定时器ID
let intervalId: number;
//离开键盘
function cinTapEnd() {
  console.log('离开');
  clearInterval(intervalId);
}
//长按键盘
function logTapCinKey(value: string = '') {
  // 设置定时器并保存ID
  intervalId = setInterval(() => {
    CinKey(value);
  }, 100);
}
//键盘输入
function CinKey(value: string = '') {
  if (value !== 'd') {
    pay.value.price += value;
  } else {
    if (pay.value.price[pay.value.price.length - 2] === '.') {
      pay.value.price = pay.value.price.slice(0, -2);
    } else {
      pay.value.price = pay.value.price.slice(0, -1);
    }
  }
}

//初始化
function Init() {
  InitKeys();
  GetOption();
}
//初始化键盘
function InitKeys() {
  //添加1到9
  for (let i = 1; i <= 9; i++) {
    keys.value.push({
      name: i + '',
      classList: '',
      value: i + '',
    });
  }
  //添加.
  keys.value.push({
    name: '.',
    classList: '',
    value: '.',
  });
  //添加0
  keys.value.push({
    name: '0',
    classList: '',
    value: '0',
  });
  //添加删除
  keys.value.push({
    name: '<-',
    classList: '',
    value: 'd',
  });
}
//获取配置
function GetOption() {
  option.value = billStore.GetOption();
}
//获取今日数据
function GetDayData(year: number, month: number, day: number) {
  today.value = billStore.GetDayData(year, month, day);
}
//获取数据
uni.$on('dayData', function (data) {
  today.value = data;
});
//打开面板
uni.$on('openCin', function () {
  if (state.value === 1) {
    cinTransition.value = '';
    cinMove.value = -500;
  }
  setTimeout(() => {
    cinTransition.value = 'all ease 0.5s';
    cinMove.value = 0;
    state.value = -1;
    tapClick.value = -1;
    modBtn = false;
  }, 100);
});
//详细日历
uni.$on('calendarShow', function (btn) {
  if (btn) {
    if (state.value === 1) {
      cinTransition.value = '';
    } else {
      cinTransition.value = 'all ease 1s';
    }
    cinMove.value = -500;
  } else {
    if (cinMove.value > 0) {
      cinTransition.value = '';
      cinMove.value = -500;
    }
    setTimeout(() => {
      cinTransition.value = 'all ease 0.5s';
      cinMove.value = 0;
      state.value = -1;
      tapClick.value = -1;
      modBtn = false;
    }, 100);
  }
});
</script>

<style scoped>
.cin {
  left: 50%;
  position: absolute;
  opacity: 1;
  width: 100%;
  height: 100%;
  background-color: white;
}
.cin-active {
  pointer-events: none;
}
.cin-key-box {
  width: 100%;
  height: 35%;
  display: flex;
  flex-direction: column;
  transition: all ease 0.5s;
  border-top: 5px solid white;
}
.cin-key-box-up {
  width: 100%;
  height: 60%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.cin-key-value {
  width: 45%;
  height: 100%;
  margin-left: 4%;
  display: flex;
  justify-content: left;
  align-items: center;
  font-size: 50rpx;
  overflow-x: auto;
  white-space: nowrap;
}
.cin-name {
  width: 45%;
  height: 50%;
  margin-right: 4%;
  font-size: 45rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.2);
}
.cin-tap {
  width: 100%;
  height: 40%;
  display: flex;
  flex-direction: row;
  align-items: center;
  position: relative;
  padding-inline: 2%;
}
.cin-tap-list {
  width: 76%;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  overflow-x: auto;
}
.cin-tap-item {
  flex: 0 0 auto;
  cursor: pointer;
  min-width: 100rpx;
  height: 50%;
  display: flex;
  font-size: 25rpx;
  justify-content: center;
  align-items: center;
  margin: 1%;
  border-radius: 10rpx;
  transition: transform ease 0.5s;
}
.cin-tap-item:active {
  opacity: 0.8;
}
.cin-tap-item-up {
  transform: translateY(-50%);
}
.add-tap-input {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 15%;
  height: 48%;
  font-size: 30rpx;
  z-index: 2;
  margin: 1%;
  border-radius: 10rpx;
  border: 1px dashed rgb(87, 189, 105);
  color: rgb(87, 189, 105);
  font-size: 30rpx;
  right: 5.5%;
  position: absolute;
  text-align: center;
}

.add-tap:active {
  opacity: 0.8;
}
.keys {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 65%;
  display: flex;
  border-top: 1rpx solid rgb(221, 221, 221);
  justify-content: center;
  align-content: center;
  flex-wrap: wrap;
  background: rgb(247, 247, 247);
}
.keyd{
  color:rgb(128,128,128);
  width: 30%;
  height: 20%;
  margin: 1.25%;
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 39rpx;
  border-radius: 10rpx;
  cursor: pointer;
}
.key{
}
.key:active {
  background-color: rgb(229, 229, 229);
}
</style>
